<?php
namespace App\Service;


use App\Constants\ErrorCode;
use App\Constants\KeyConstants;
use App\Event\UserSignuped;
use App\Exception\BusinessException;
use App\Model\User;
use App\Model\UserDynamic;
use App\Service\Instance\JwtInstance;
use Hyperf\Cache\CacheManager;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Utils\ApplicationContext;
use Psr\EventDispatcher\EventDispatcherInterface;

class UserService extends Service
{
    #[Inject]
    private EventDispatcherInterface $eventDispatcher;

    #[Inject]
    protected CacheManager $cacheManager;

    #[Inject]
    protected \App\Components\CacheManager $cacheManagerV2;

    /**
     * 批量操作.
     *
     * @param $ids
     * @return array
     */
    public function getMultiUserInfosFromCache($ids)
    {
        $userModel = new User();

        return $this->cacheManagerV2->multiCall(function ($targetIds) use ($userModel) {
            return $userModel->getUserInfos($targetIds);
        }, $ids, 'user', env('APP_ENV') == 'dev' ? 60 : 600, 'id', 'other');
    }

    /**
     * 获取用户信息
     * @param $id
     */
    public function getUserInfoFromCache($id){
        $userModel = new User();
        $userInfo = $this->cacheManager->call(function () use ($userModel,$id){
            return $userModel->getUserInfo($id);
        },sprintf(KeyConstants::UserInfo,$id),env('APP_ENV') == 'dev' ? 10 : 3600,'other');
        if (!$userInfo){
            //当用户第一次查询 后续缓存结束之后都会用这个数据判断
            throw new  BusinessException(ErrorCode::USER_NOT_EXISTS);
        }
        return $userInfo;
    }

    /**
     * @param $email
     * @param $password
     */
    public function login($email,$password){
// 校验用户是否存在
        $user = User::query()->where(['email' => $email])->first();
        if (empty($user)) {
            throw new BusinessException(ErrorCode::USER_NOT_EXISTS);
        }

        // 校验密码是否正确
        if (! password_verify($password, $user['password'])) {
            throw new BusinessException(ErrorCode::PASSWORD_ERROR);
        }

        // jwt 编码获取 token 和用户信息
        $token = JwtInstance::instance()->encode($user);
        $userInfo = JwtInstance::instance()->getUser();
        return [
            $userInfo,$token
        ];
    }

    /**
     * 登陆
     * @param $param
     */
    public function signup($param)
    {
        //开启事物
        Db::beginTransaction();
        try {
            $userModel = new User();
            $userModel->email = $param['email'];
            $userModel->password = password_hash($param['password'],PASSWORD_DEFAULT);
            $userModel->pic = "test.png";
            $userModel->nickname = "api_".rand(1111,9999);
            $userModel->save();
            //添加dynamic表
            $userDynamicModel = new UserDynamic();
            $userDynamicModel->uid = $userModel->id;
            $userDynamicModel->save();
            Db::commit();
        }catch (\Exception $e){
            Db::rollBack();
            $this->logger->error($e->getMessage());
            throw new BusinessException(ErrorCode::SERVER_ERROR);
        }
        // 获取token
        $token = JwtInstance::instance()->encode($userModel);
        $userInfo = JwtInstance::instance()->getUser();//获取用户详情

        // 事件触发
        $this->eventDispatcher->dispatch(new UserSignuped($userInfo));

        //返回数据
        return [
            $userInfo,
            $token,
        ];
    }
}